package com.lt.flashcard.model.service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.zkoss.zkplus.hibernate.HibernateUtil;

import com.lt.flashcard.model.entity.Tag;

/**
 * Provide utility to interact with taging
 * 
 * @author ocsen
 * @version 1.0
 * @created 15-Aug-2012 21:38:20
 */
public class TagService extends BasicDAO<Tag> {

    public TagService() {
        super(Tag.class);
    }

    /**
     * Get list of root tag that defined by admin
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<Tag> getRootAdminTagList() {
        Session ses = HibernateUtil.currentSession();
        return ses.createCriteria(Tag.class).add(Restrictions.eq("reserved", 1)).add(Restrictions.isNull("parent"))
                .addOrder(Order.asc("name")).list();
    }

    /**
     * Get list of admin tag list
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<Tag> getAdminTagList() {
        Session ses = HibernateUtil.currentSession();
        return ses.createCriteria(Tag.class).add(Restrictions.eq("reserved", 1)).addOrder(Order.asc("name")).list();
    }

    /**
     * Get list of all tags in system
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<Tag> getTagList() {
        Session ses = HibernateUtil.currentSession();
        return ses.createCriteria(Tag.class).addOrder(Order.asc("name")).list();
    }

    /**
     * Find tag by name
     * 
     * @param name
     * @return
     */
    public Tag findTagByName(String name) {
        return (Tag) createCriteria().add(Restrictions.eq("name", name)).uniqueResult();
    }

    /**
     * Find tags with name
     * 
     * @param names
     * @return
     */
    public List<Tag> getTagByName(Collection<String> names) {
        return createCriteria().add(Restrictions.in("name", names)).list();
    }

    @SuppressWarnings("unchecked")
    public List<Tag> getByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Collections.emptyList();
        }
        return createCriteria().add(Restrictions.in("id", ids)).list();
    }
}